package com.atguigu.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @Author: liuaojun
 * @CreateTime: 2025-01-15
 * @Description:
 * @Version: 1.0
 */
@Component
@Aspect
public class Mylogging {
    @Pointcut("execution(* com.atguigu.aop.ClceImpl.*(..))")
    public void myPointCut(){}

    //@Before("myPointCut()")
    public void beforeMethod(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("前置通知===>"+name+"()方法正在执行，参数有"+ Arrays.toString(args));

    }
    //@After("myPointCut()")
    public void afterMethod(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("后置通知===>"+name+"()方法正在执行，参数有"+ Arrays.toString(args));

    }

    //@AfterThrowing(value = "myPointCut()",throwing = "ex")
    public void methodAfterReturning(JoinPoint joinPoint,Exception ex) {
        String name = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("异常通知===>"+name+"()方法在抛出异常后执行，异常有"+ ex);
    }

    //@AfterReturning(value = "myPointCut()",returning = "rs")
    public void methodAfterReturning(JoinPoint joinPoint,Object rs) {
        String name = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("返回通知===>"+name+"()方法返回，结果："+ rs);
    }

    @Around("myPointCut()")
    public Object aroundMethod(ProceedingJoinPoint pjp){
        String name = pjp.getSignature().getName();
        Object[] args = pjp.getArgs();
        Object rs=null;

        try {
            System.out.println("前置通知===>"+name+"()方法正在执行，参数有"+ Arrays.toString(args));
            rs = pjp.proceed();
            System.out.println("返回通知=====>"+name+"()返回结果后执行,rs:"+rs);
        } catch (Throwable e) {
            System.out.println("异常通知===>"+name+"()抛出异常后执行，EX："+ e);
            throw new RuntimeException(e);
        } finally {
            System.out.println("后置通知===>"+name+"()方法正在执行，参数有"+ Arrays.toString(args));
        }
        return rs;

    }




}
